package dtos

import (
	"encoding/json"
	"errors"
	"log"

	"github.com/beego/beego/v2/core/validation"
	beecontext "github.com/beego/beego/v2/server/web/context"
)

func Bind[T any](params *T, ctx *beecontext.Context) error {
	body := ctx.Input.RequestBody

	// 从请求体中解析参数
	if err := json.Unmarshal(body, params); err != nil {
		return err
	}

	err := ValidateParams(params)

	if err != nil {
		return err
	}

	return nil
}

func ValidateParams(params interface{}) error {
	valid := validation.Validation{}

	// 进行数据验证
	b, err := valid.Valid(params)
	if err != nil {
		// 处理验证过程中的错误，比如记录日志等
		return err
	}

	if !b {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
			return errors.New(err.Message)
		}
	}

	return nil
}
